/*
  Copyright © 2010  Vinícius dos Santos Oliveira

      This file is part of Touché.

      Touché is free software: you can redistribute it and/or modify
      it under the terms of the GNU Lesser General Public License as published
      by the Free Software Foundation, either version 3 of the License, or
      (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU Lesser General Public License for more details.

      You should have received a copy of the GNU Lesser General Public License
      along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */

#include "stageactorlink.h"
#include "stageactor.h"
#include "colaborativecontroller.h"
using namespace Touche;

QList<StageActorLink *> StageActorLink::m_links;
QMutex StageActorLink::mutex(QMutex::Recursive);

StageActorLink::StageActorLink(StageActor *item1, StageActor *item2)
{
    m_actors[0] = item1;
    m_actors[1] = item2;
    connect(item1, SIGNAL(destroyed()), this, SLOT(deleteLater()));
    connect(item2, SIGNAL(destroyed()), this, SLOT(deleteLater()));
    m_links << this;

    ColaborativeController::getInstance()->colaborateLink(item1->m_element->id, item2->m_element->id);
}

StageActorLink::~StageActorLink()
{
}

QVector<StageActor *> StageActorLink::actors()
{
    QVector<StageActor *> actors(2);
    actors[0] = m_actors[0];
    actors[1] = m_actors[1];
    return actors;
}

const QList<StageActorLink *> &StageActorLink::links()
{
    return m_links;
}

StageActorLink *StageActorLink::exists(StageActor *src, StageActor *sink)
{
    if(!src || !sink){
        return NULL;
    }
    for(QListIterator<StageActorLink *> i(m_links);i.hasNext();){
        StageActorLink *link = i.next();
        if(link->sink(src) == sink){
            return link;
        }
    }
    return NULL;
}

void StageActorLink::eraseFromList(StageActorLink *link)
{
    mutex.lock();
    for(QList<StageActorLink *>::iterator i = m_links.begin();i != m_links.end();++i){
        if(*i == link){
            m_links.erase(i);
            link->deleteLater();
            break;
        }
    }
    mutex.unlock();
}
